package com.buaa.divinationmaster.interpretation;

import android.content.Context;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 生活化解读器
 * 专门负责将占卜术语转换为贴近生活的表达方式
 * 
 * 核心功能：
 * - 专业术语词汇替换
 * - 语言风格调整
 * - 生活化场景映射
 * - 情感语调优化
 */
public class LifestyleInterpreter {
    
    private static final String TAG = "LifestyleInterpreter";
    
    private Context context;
    private Random random;
    
    // 术语映射表
    private Map<String, TermMapping> professionalToLifestyle;
    private Map<String, List<String>> categorySpecificTerms;
    private Map<String, List<String>> emotionalExpressions;
    private Map<String, List<String>> transitionPhrases;
    
    /**
     * 术语映射数据结构
     */
    public static class TermMapping {
        private List<String> casualExpressions;    // 日常表达
        private List<String> contextualMeanings;   // 上下文含义
        private String emotionalTone;              // 情感色调
        
        public TermMapping(List<String> casual, List<String> contextual, String tone) {
            this.casualExpressions = casual;
            this.contextualMeanings = contextual;
            this.emotionalTone = tone;
        }
        
        public List<String> getCasualExpressions() { return casualExpressions; }
        public List<String> getContextualMeanings() { return contextualMeanings; }
        public String getEmotionalTone() { return emotionalTone; }
    }
    
    public LifestyleInterpreter(Context context) {
        this.context = context;
        this.random = new Random();
        initializeTermMappings();
        initializeCategoryTerms();
        initializeEmotionalExpressions();
        initializeTransitionPhrases();
    }
    
    /**
     * 将专业解读转换为生活化表达
     */
    public String convertToLifestyle(String professionalText, 
                                   ContextAnalyzer.QuestionCategory category,
                                   InterpretationEngine.InterpretationStyle style) {
        
        if (professionalText == null || professionalText.trim().isEmpty()) {
            return "";
        }
        
        String result = professionalText;
        
        // 1. 替换专业术语
        result = replaceProfessionalTerms(result);
        
        // 2. 应用分类特定的表达
        result = applyCategorySpecificExpressions(result, category);
        
        // 3. 调整语言风格
        result = adjustLanguageStyle(result, style);
        
        // 4. 添加过渡短语让语言更自然
        result = addTransitionPhrases(result);
        
        // 5. 优化句子结构
        result = optimizeSentenceStructure(result);
        
        return result.trim();
    }
    
    /**
     * 转换特定章节为生活化表达
     */
    public String convertSectionToLifestyle(String sectionTitle, String content,
                                          ContextAnalyzer.QuestionCategory category,
                                          InterpretationEngine.InterpretationStyle style) {
        
        // 转换章节标题
        String lifestyleTitle = convertSectionTitle(sectionTitle);
        
        // 转换内容
        String lifestyleContent = convertToLifestyle(content, category, style);
        
        if (lifestyleContent.isEmpty()) return "";
        
        return String.format("**%s**\n%s", lifestyleTitle, lifestyleContent);
    }
    
    /**
     * 替换专业术语为生活化表达
     */
    private String replaceProfessionalTerms(String text) {
        String result = text;
        
        for (Map.Entry<String, TermMapping> entry : professionalToLifestyle.entrySet()) {
            String professionalTerm = entry.getKey();
            TermMapping mapping = entry.getValue();
            
            if (result.contains(professionalTerm)) {
                // 随机选择一个日常表达
                String casualExpression = getRandomExpression(mapping.getCasualExpressions());
                result = result.replace(professionalTerm, casualExpression);
            }
        }
        
        return result;
    }
    
    /**
     * 应用分类特定的表达方式
     */
    private String applyCategorySpecificExpressions(String text, ContextAnalyzer.QuestionCategory category) {
        List<String> categoryTerms = categorySpecificTerms.get(category.getName());
        if (categoryTerms == null) return text;
        
        String result = text;
        
        // 根据分类添加相关的生活化表达
        switch (category) {
            case LOVE_RELATIONSHIP:
                result = enhanceWithLoveExpressions(result);
                break;
            case CAREER_WORK:
                result = enhanceWithCareerExpressions(result);
                break;
            case HEALTH_WELLBEING:
                result = enhanceWithHealthExpressions(result);
                break;
            case MONEY_FINANCE:
                result = enhanceWithFinanceExpressions(result);
                break;
            case PERSONAL_GROWTH:
                result = enhanceWithGrowthExpressions(result);
                break;
            default:
                result = enhanceWithGeneralExpressions(result);
                break;
        }
        
        return result;
    }
    
    /**
     * 调整语言风格
     */
    private String adjustLanguageStyle(String text, InterpretationEngine.InterpretationStyle style) {
        String result = text;
        
        switch (style) {
            case FRIENDLY:
                result = makeFriendly(result);
                break;
            case PROFESSIONAL:
                result = makeProfessionalButAccessible(result);
                break;
            case ENCOURAGING:
                result = makeEncouraging(result);
                break;
            case REALISTIC:
                result = makeRealistic(result);
                break;
            case MYSTICAL:
                result = makeMysticalButUnderstandable(result);
                break;
        }
        
        return result;
    }
    
    /**
     * 添加过渡短语
     */
    private String addTransitionPhrases(String text) {
        String[] sentences = text.split("\\.");
        if (sentences.length < 2) return text;
        
        StringBuilder result = new StringBuilder();
        List<String> transitions = transitionPhrases.get("general");
        
        for (int i = 0; i < sentences.length; i++) {
            String sentence = sentences[i].trim();
            if (sentence.isEmpty()) continue;
            
            result.append(sentence);
            
            // 在句子之间添加过渡短语
            if (i < sentences.length - 1 && random.nextFloat() < 0.3) {
                String transition = getRandomExpression(transitions);
                result.append("。").append(transition);
            } else if (i < sentences.length - 1) {
                result.append("。");
            }
        }
        
        return result.toString();
    }
    
    /**
     * 优化句子结构
     */
    private String optimizeSentenceStructure(String text) {
        String result = text;
        
        // 避免过长的句子
        result = breakLongSentences(result);
        
        // 合并过短的句子
        result = mergeShortSentences(result);
        
        // 添加适当的标点符号
        result = optimizePunctuation(result);
        
        return result;
    }
    
    /**
     * 转换章节标题
     */
    private String convertSectionTitle(String sectionTitle) {
        Map<String, String> titleMappings = new HashMap<>();
        titleMappings.put("牌面解读", "卡牌的含义");
        titleMappings.put("位置含义", "在这个位置的意义");
        titleMappings.put("综合分析", "整体来看");
        titleMappings.put("总结建议", "给你的建议");
        titleMappings.put("注意事项", "需要注意的地方");
        titleMappings.put("未来发展", "未来的趋势");
        titleMappings.put("行动建议", "可以采取的行动");
        
        return titleMappings.getOrDefault(sectionTitle, sectionTitle);
    }
    
    // 分类特定的表达增强方法
    private String enhanceWithLoveExpressions(String text) {
        String result = text;
        result = result.replace("感情运势", "感情方面");
        result = result.replace("桃花运", "遇到心仪对象的机会");
        result = result.replace("正缘", "真正适合的人");
        result = result.replace("烂桃花", "不太合适的人");
        return result;
    }
    
    private String enhanceWithCareerExpressions(String text) {
        String result = text;
        result = result.replace("事业运", "工作发展");
        result = result.replace("贵人运", "得到他人帮助的机会");
        result = result.replace("小人", "可能会有阻碍的人或事");
        result = result.replace("官运", "晋升机会");
        return result;
    }
    
    private String enhanceWithHealthExpressions(String text) {
        String result = text;
        result = result.replace("身体状况", "健康情况");
        result = result.replace("气血", "精神状态");
        result = result.replace("五脏六腑", "身体各个方面");
        return result;
    }
    
    private String enhanceWithFinanceExpressions(String text) {
        String result = text;
        result = result.replace("财运", "财务状况");
        result = result.replace("正财", "稳定收入");
        result = result.replace("偏财", "额外收入机会");
        result = result.replace("破财", "可能的支出");
        return result;
    }
    
    private String enhanceWithGrowthExpressions(String text) {
        String result = text;
        result = result.replace("修行", "自我提升");
        result = result.replace("业障", "需要克服的困难");
        result = result.replace("福报", "好的结果");
        return result;
    }
    
    private String enhanceWithGeneralExpressions(String text) {
        String result = text;
        result = result.replace("运势", "情况");
        result = result.replace("吉凶", "好坏");
        result = result.replace("化解", "解决");
        return result;
    }
    
    // 风格调整方法
    private String makeFriendly(String text) {
        String result = text;
        result = result.replace("您", "你");
        result = result.replace("应当", "可以");
        result = result.replace("必须", "最好");
        result = result.replace("务必", "要记得");
        
        // 添加友好的语气词
        if (random.nextFloat() < 0.2) {
            result = result.replace("。", "哦。");
        }
        
        return result;
    }
    
    private String makeProfessionalButAccessible(String text) {
        String result = text;
        result = result.replace("俺", "我");
        result = result.replace("咱", "我们");
        // 保持正式但不过于严肃
        return result;
    }
    
    private String makeEncouraging(String text) {
        String result = text;
        result = result.replace("困难", "挑战");
        result = result.replace("问题", "机会");
        result = result.replace("失败", "学习的机会");
        result = result.replace("不好", "可以改善");
        
        // 添加鼓励性语句
        if (text.contains("建议")) {
            result = result.replace("建议", "相信你可以");
        }
        
        return result;
    }
    
    private String makeRealistic(String text) {
        String result = text;
        result = result.replace("一定会", "很可能会");
        result = result.replace("绝对", "通常");
        result = result.replace("必然", "往往");
        return result;
    }
    
    private String makeMysticalButUnderstandable(String text) {
        String result = text;
        result = result.replace("显示", "揭示");
        result = result.replace("表示", "暗示");
        result = result.replace("说明", "告诉我们");
        // 保持一定的神秘感但确保易懂
        return result;
    }
    
    // 辅助方法
    private String getRandomExpression(List<String> expressions) {
        if (expressions == null || expressions.isEmpty()) {
            return "";
        }
        return expressions.get(random.nextInt(expressions.size()));
    }
    
    private String breakLongSentences(String text) {
        String[] sentences = text.split("。");
        StringBuilder result = new StringBuilder();
        
        for (int i = 0; i < sentences.length; i++) {
            String sentence = sentences[i].trim();
            if (sentence.isEmpty()) continue;
            
            if (sentence.length() > 60) {
                // 尝试在适当位置分割长句
                String[] parts = sentence.split("，");
                if (parts.length > 2) {
                    for (int j = 0; j < parts.length; j++) {
                        result.append(parts[j].trim());
                        if (j < parts.length - 1) {
                            if (j % 2 == 1) {
                                result.append("。");
                            } else {
                                result.append("，");
                            }
                        }
                    }
                } else {
                    result.append(sentence);
                }
            } else {
                result.append(sentence);
            }
            
            if (i < sentences.length - 1) {
                result.append("。");
            }
        }
        
        return result.toString();
    }
    
    private String mergeShortSentences(String text) {
        String[] sentences = text.split("。");
        StringBuilder result = new StringBuilder();
        
        for (int i = 0; i < sentences.length; i++) {
            String sentence = sentences[i].trim();
            if (sentence.isEmpty()) continue;
            
            result.append(sentence);
            
            // 如果当前句子很短且下一句也很短，用逗号连接
            if (i < sentences.length - 1) {
                String nextSentence = sentences[i + 1].trim();
                if (sentence.length() < 15 && nextSentence.length() < 15 && !nextSentence.isEmpty()) {
                    result.append("，");
                } else {
                    result.append("。");
                }
            }
        }
        
        return result.toString();
    }
    
    private String optimizePunctuation(String text) {
        String result = text;
        
        // 确保适当的标点符号
        result = result.replaceAll("。{2,}", "。");
        result = result.replaceAll("，{2,}", "，");
        result = result.replaceAll("！{2,}", "！");
        result = result.replaceAll("\\?{2,}", "？");
        
        // 确保结尾有标点符号
        if (!result.isEmpty() && !result.matches(".*[。！？]$")) {
            result += "。";
        }
        
        return result;
    }
    
    /**
     * 初始化术语映射表
     */
    private void initializeTermMappings() {
        professionalToLifestyle = new HashMap<>();
        
        // 塔罗牌术语
        professionalToLifestyle.put("正位", 
            new TermMapping(
                Arrays.asList("正面的", "积极的", "顺利的"),
                Arrays.asList("事情会朝好的方向发展", "情况比较乐观"),
                "positive"
            ));
            
        professionalToLifestyle.put("逆位",
            new TermMapping(
                Arrays.asList("相反的", "需要注意的", "有阻碍的"),
                Arrays.asList("可能会遇到一些挑战", "需要小心应对"),
                "caution"
            ));
            
        professionalToLifestyle.put("大阿卡纳",
            new TermMapping(
                Arrays.asList("重要的牌", "主要的牌"),
                Arrays.asList("代表人生中的重大主题", "具有深远影响的事情"),
                "important"
            ));
            
        professionalToLifestyle.put("小阿卡纳",
            new TermMapping(
                Arrays.asList("日常的牌", "具体的牌"),
                Arrays.asList("代表日常生活中的事情", "比较具体的情况"),
                "daily"
            ));
        
        // 易经术语
        professionalToLifestyle.put("阴爻",
            new TermMapping(
                Arrays.asList("柔性的力量", "内在的能量"),
                Arrays.asList("需要耐心等待", "适合内省和积累"),
                "gentle"
            ));
            
        professionalToLifestyle.put("阳爻",
            new TermMapping(
                Arrays.asList("积极的力量", "外在的能量"),
                Arrays.asList("适合主动出击", "时机比较成熟"),
                "active"
            ));
            
        professionalToLifestyle.put("变爻",
            new TermMapping(
                Arrays.asList("变化的关键", "转折点"),
                Arrays.asList("情况会发生变化", "需要注意的重点"),
                "change"
            ));
        
        // 通用占卜术语
        professionalToLifestyle.put("时机",
            new TermMapping(
                Arrays.asList("合适的时候", "机会"),
                Arrays.asList("什么时候行动比较好", "把握合适的机会"),
                "timing"
            ));
            
        professionalToLifestyle.put("能量",
            new TermMapping(
                Arrays.asList("影响力", "力量", "氛围"),
                Arrays.asList("周围的情况", "环境的影响"),
                "influence"
            ));
    }
    
    /**
     * 初始化分类特定术语
     */
    private void initializeCategoryTerms() {
        categorySpecificTerms = new HashMap<>();
        
        categorySpecificTerms.put("LOVE_RELATIONSHIP", Arrays.asList(
            "感情", "关系", "伴侣", "约会", "婚姻", "分手", "复合"
        ));
        
        categorySpecificTerms.put("CAREER_WORK", Arrays.asList(
            "工作", "职业", "同事", "上司", "项目", "晋升", "跳槽"
        ));
        
        categorySpecificTerms.put("HEALTH_WELLBEING", Arrays.asList(
            "健康", "身体", "精神", "休息", "运动", "医生", "治疗"
        ));
        
        categorySpecificTerms.put("MONEY_FINANCE", Arrays.asList(
            "金钱", "投资", "收入", "支出", "理财", "债务", "储蓄"
        ));
        
        categorySpecificTerms.put("PERSONAL_GROWTH", Arrays.asList(
            "成长", "学习", "目标", "梦想", "技能", "经验", "智慧"
        ));
    }
    
    /**
     * 初始化情感表达
     */
    private void initializeEmotionalExpressions() {
        emotionalExpressions = new HashMap<>();
        
        emotionalExpressions.put("positive", Arrays.asList(
            "很好", "不错", "令人高兴", "值得庆祝", "让人欣慰"
        ));
        
        emotionalExpressions.put("negative", Arrays.asList(
            "需要注意", "要小心", "可能会有困难", "需要谨慎对待"
        ));
        
        emotionalExpressions.put("neutral", Arrays.asList(
            "比较平稳", "没有太大变化", "保持现状", "稳定发展"
        ));
        
        emotionalExpressions.put("encouraging", Arrays.asList(
            "你可以做到", "相信自己", "不要放弃", "一切都会好起来"
        ));
    }
    
    /**
     * 初始化过渡短语
     */
    private void initializeTransitionPhrases() {
        transitionPhrases = new HashMap<>();
        
        transitionPhrases.put("general", Arrays.asList(
            "另外", "同时", "不过", "另一方面", "值得一提的是", "需要注意的是"
        ));
        
        transitionPhrases.put("contrast", Arrays.asList(
            "但是", "然而", "相反", "不过", "另一方面"
        ));
        
        transitionPhrases.put("addition", Arrays.asList(
            "此外", "另外", "同时", "而且", "还有"
        ));
        
        transitionPhrases.put("conclusion", Arrays.asList(
            "总的来说", "综合来看", "最后", "总结一下"
        ));
    }
}
